<?php
/**
 *  @department : Commercial development.
 *  @description : This file is part of [BWMS].
 *  DZ all rights reserved.
 */
include_once 'helper_common.php';
use service\OssService;

// 应用公共文件  --  业务支持脚手架方法

//转化时间区间
if (!function_exists('changeTime')) {
    function changeTime($start, $over)
    {
        $start = strtotime($start);
        $over = strtotime($over);
        if (empty($start) && empty($over)) {
            return ['status' => false];
        }
        if ($over == $start) {
            return ['status' => true, 'area' => ['between', [$start, $start + 24 * 60 * 60]]];
        }
        if (empty($start)) {
            return ['status' => true, 'area' => ['lt', $over]];
        }
        if (empty($over)) {
            return ['status' => true, 'area' => ['gt', $start]];
        }

        return ['status' => true, 'area' => ['between', [$start, $over]]];
    }
}

if (!function_exists('filterData')) {
    /**
     * 过滤信息.
     * @param  array $data 前端提交过来的数据
     * @return array
     */
    function filterData($data)
    {
        $arr = [];
        foreach ($data as $key => $value) {
            $arr[$key] = is_array($value) ? filterData($value) : addslashes(trim(htmlspecialchars(nl2br($value))));
        }
        return $arr;
    }
}

if (!function_exists('getSplitPageInfo')) {
    /**
     * 获取分页信息.
     * @param  int   $page      页码
     * @param  int   $page_size 每页显示记录数
     * @return array
     */
    function getSplitPageInfo(int $page, int $page_size)
    {
        //参数为零则采用默认值
        $page = empty($page) || !is_numeric($page) || $page < 1 ? 1 : $page;
        $page_size = empty($page_size) || !is_numeric($page_size) ? 20 : $page_size;
        $page_start = $page_size * ($page - 1);

        return ['page_start' => $page_start, 'page_size' => $page_size];
    }
}

if (!function_exists('readExcelFiles')) {
    /**
     * 读取上传的excel文件.
     * @param  array $file 上传的文件数据
     * @return array
     */
    function readExcelFiles($file)
    {
        $file = $file->validate(['ext' => 'xlsx,xls,csv'])->move(env('ROOT_PATH') . 'public/uploadFile/excel');

        if (empty($file)) {
            return ['status' => false, 'message' => '导入失败!请检查文件后缀或者文件大小'];
        }

        $filename = $file->getSaveName();
        $filepath = env('ROOT_PATH') . 'public/uploadFile/excel/' . $filename;

        //自动获取文件的类型提供给phpexcel用
        $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));

        if ('xlsx' == $extension) {
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
            //加载文件内容,编码utf-8
            $objPHPExcel = $objReader->load($filepath, $encode = 'utf-8');
        } elseif ('xls' == $extension) {
            $objReader = \PHPExcel_IOFactory::createReader('Excel5');
            $objPHPExcel = $objReader->load($filepath, $encode = 'utf-8');
        } else {
            return ['status' => false, 'message' => '请上传excel格式的文件!'];
        }

        return ['status' => true, 'source' => $objPHPExcel, 'file_type' => 'excel'];
    }
}

if (!function_exists('exportFile')) {
    /**
     * 导出数据文件.
     * @param string $file_path 模板文路径
     * @param array  $data      被写入数据
     */
    function exportFile($file_path, $data, $file_name = '', $start_row, $way = '')
    {
        //读取模板数据
        $file = $file_path;
        if (!file_exists($file)) {
            return ['status' => false, 'message' => '找不到模板文件' . $file];
        }

        $obj = \PHPExcel_IOFactory::load($file);
        $sheet = $obj->getActiveSheet();

        $row = sizeof($data);
        for ($j = $start_row; $j < $row + $start_row; ++$j) {
            $i = 'A';
            foreach ($data[$j - $start_row] as $key => $value) {
                if (is_numeric($value)) {
                    $sheet->setCellValueExplicit($i . $j, $value, \PHPExcel_Cell_DataType::TYPE_STRING)
                        ->getStyle($i . $j)->getNumberFormat()->setFormatCode('@');
                } else {
                    $sheet->setCellValue($i . $j, $value);
                }
                ++$i;
            }
        }

        if ('' == $file_name) {
            $file_name = date('YmdHis', time());
        }

        ob_end_clean();
        $objWriter = \PHPExcel_IOFactory::createWriter($obj, 'Excel2007');

        if (!empty($way)) {
            $objWriter->save($way);
            return true;
        }

        header('Content-Type: application/force-download');
        header('Content-Type: application/octet-stream');
        header('Content-Type: application/download');
        header('Content-Disposition:inline;filename="' . $file_name . '.xlsx"');
        header('Content-Transfer-Encoding: binary');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: no-cache');
        $objWriter->save('php://output');
        return ['status' => true];
    }
}

if (!function_exists('float_cmp')) {
    //浮点数科学的比较方式, 解决PHP浮点数比较的问题
    function float_cmp($f1, $f2, $precision = 10)
    {
        $e = pow(10, $precision);
        $i1 = intval($f1 * $e);
        $i2 = intval($f2 * $e);
        return $i1 == $i2;
    }
}

if (!function_exists('getClientIp')) {
    //获取客户端ip
    function getClientIp()
    {
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } elseif (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        } elseif (!empty(getenv('HTTP_X_FORWARDED_FOR'))) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (!empty(getenv('HTTP_CLIENT_IP'))) {
            $ip = getenv('HTTP_CLIENT_IP');
        } elseif (!empty(getenv('REMOTE_ADDR'))) {
            $ip = getenv('REMOTE_ADDR');
        } else {
            $ip = '0.0.0.0';
        }
        return $ip;
    }
}

if (!function_exists('uploadFile')) {
    //系统公共文件上传 -- 集成本地上传与oss上传, 本地存储时, 文件存储在发送path_route中, 否则收录在cache文件目录(多节点下不适用)
    function uploadFile($file_real_path, $real_name, $path_route = '', $file_name = '')
    {
        //判断默认存储方式
        $storage_type = Config::get('oss.storage_type_default');

        //首先进行文件对象在某个位置的存储与处理
        if (empty($file_name)) {
            $file_name = date('YmdHis') . rand(0, 9999);
        }

        //根据存储方式, 判断是否要上传oss并返回oss外链路径, 或者返回本地的图片部分路由
        switch ($storage_type) {
        case 'local':
            if (empty($path_route)) {
                if (!file_exists(env('ROOT_PATH') . '/' . env('UPLOAD_DIR'))) {
                    @mkdir(env('ROOT_PATH') . '/' . env('UPLOAD_DIR'), 0777, true);
                }
                $file_path = env('ROOT_PATH') . '/' . env('UPLOAD_DIR');
            } else {
                //检查该图片路径是否存在
                if (!file_exists(Config::get('path.UPLOAD_PATH') . $path_route)) {
                    @mkdir(Config::get('path.UPLOAD_PATH') . $path_route, 0777, true);
                }
                $file_path = Config::get('path.UPLOAD_PATH') . $path_route;
            }

            // $info = $file_obj->move($file_path, $file_name);

            // if (empty($info)) {
            //     return ['status' => false, 'message' => '文件上传失败'];
            // }
            $result = copy($file_real_path, $file_path . $file_name);

            if (!$result) {
                return ['status' => false, 'message' => '文件上传失败'];
            }

            //本地存储成功, 返回部分图片路由
            return ['status' => true, 'url' => $path_route . '/' . $info->getSavename()];
            break;
        case 'qiniu':
            $file_path = $file_real_path;
            $ext = pathinfo($real_name, PATHINFO_EXTENSION);  //后缀

            $upload_result = OssService::qiniu($file_name . '.' . $ext, $file_path, true);

            if (false === $upload_result) {
                return ['status' => false, 'message' => '文件上传失败'];
            }
            return ['status' => true, 'url' => $upload_result['url']];
            break;
    }
    }
}

if (!function_exists('readExcelWithPic')) {
    /**
     * 读取上传的excel文件.
     * @param  array $file 上传的文件数据
     * @return array
     */
    function readExcelWithPic($file, $pic_save_path)
    {
        $file = $file->validate(['ext' => 'xlsx,xls,csv'])->move(env('ROOT_PATH') . 'public/uploadFile/excel');

        if (empty($file)) {
            return ['status' => false, 'message' => '导入失败!请检查文件后缀或者文件大小'];
        }

        $filename = $file->getSaveName();
        $filepath = env('ROOT_PATH') . 'public/uploadFile/excel/' . $filename;

        //自动获取文件的类型提供给phpexcel用
        // $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        $inputFileType = PHPExcel_IOFactory::identify($filepath);
        $imageFilePath = $pic_save_path;

        if ('Excel2007' == $inputFileType) {
            $objReader = \PHPExcel_IOFactory::createReader($inputFileType);
            //加载文件内容,编码utf-8
            $objPHPExcel = $objReader->load($filepath, $encode = 'utf-8');
            $sheet = $objPHPExcel->getSheet(0);
            $data = filterData($sheet->toArray());
            //处理图片
            foreach ($sheet->getDrawingCollection() as $img) {
                //以下是excel2007(xlsx)的图片解决方案,2005需要再开发,工期很赶
                list($startColumn, $startRow) = PHPExcel_Cell::coordinateFromString($img->getCoordinates()); //获取图片所在行和列

                //excel处理时文件的绝对路径名
                $imageFileName = uniqid() . $img->getIndexedFilename();

                //获取文件在excel相对位置
                $file_excel_in_name = $img->getPath();

                $pic_save_path = $imageFilePath . '/' . $imageFileName;

                //组建要存入数据库的
                $startColumn = ABC2decimal($startColumn); //由于图片所在位置的列号为字母，转化为数字
                // $data[$startRow - 1][$startColumn] = $imageFileName; //把图片名字插入到数组中
                $data[$startRow - 1][$startColumn] = $pic_save_path; //把图片名字插入到数组中
            }
        } elseif ('Excel5' == $inputFileType) {
            $objReader = \PHPExcel_IOFactory::createReader('Excel5');
            $objPHPExcel = $objReader->load($filepath, $encode = 'utf-8');
            $sheet = $objPHPExcel->getSheet(0);
            $data = filterData($sheet->toArray());

            $size = count($data[0]);

            foreach ($sheet->getDrawingCollection() as $img) {
                $cell = PHPExcel_Cell::coordinateFromString($img->getCoordinates()); //获取图片所在行和列
                $startColumn = $cell[0];
                $startRow = $cell[1];

                $imageFileName = uniqid() . $img->getCoordinates();

                switch ($img->getMimeType()) {
                    case 'image/jpg':
                        $imageFileName .= '.jpg';
                        // dump($imageFileName);
                        imagejpeg($img->getImageResource(), $imageFilePath . '/' . $imageFileName);
                        break;
                    case 'image/gif':
                        $imageFileName .= '.gif';
                        imagegif($img->getImageResource(), $imageFilePath . '/' . $imageFileName);
                        break;
                    case 'image/png':
                        $imageFileName .= '.png';
                        imagepng($img->getImageResource(), $imageFilePath . '/' . $imageFileName);
                        break;
                    default:
                        $imageFileName .= '.png';
                        imagepng($img->getImageResource(), $imageFilePath . '/' . $imageFileName);
                        break;
                }

                $result = uploadFile($imageFilePath . '/' . $imageFileName, $imageFileName);

                if (!$result['status']) {
                    return ['status' => false, 'message' => '图片上传失败'];
                }

                $startColumn = ABC2decimal($startColumn); //由于图片所在位置的列号为字母，转化为数字
                $data[$startRow - 1][$startColumn] = $imageFilePath . '/' . $imageFileName; //把图片插入到数组中
                $data[$startRow - 1][$size] = $result['url']; //OOS七牛云上的地址
            }
        } else {
            return ['status' => false, 'message' => '请上传excel格式的文件!'];
        }

        return ['status' => true, 'source' => $data, 'file_type' => 'excel'];
    }
}

if (!function_exists('ABC2decimal')) {
    //readExcelFilesWithPic子函数
    function ABC2decimal($abc)
    {
        $ten = 0;
        $len = strlen($abc);

        for ($i = 1; $i <= $len; ++$i) {
            $char = substr($abc, 0 - $i, 1); //反向获取单个字符

            $int = ord($char);

            $ten += ($int - 65) * pow(26, $i - 1);
        }

        if (2 == $len) {
            return $ten + 25;
        }
        return $ten;
    }
}

if (!function_exists('exportFileWithPic')) {
    /**
     * 导出Excel文件(包含图片).
     * @param string $file_path 模板文路径
     * @param array  $data      被写入数据
     */
    function exportFileWithPic($file_path, $data, $file_name = '', $start_row, $way = '', string $word)
    {
        //读取模板数据
        $file = $file_path;
        if (!file_exists($file)) {
            return ['status' => false, 'message' => '找不到模板文件' . $file];
        }

        $obj = \PHPExcel_IOFactory::load($file);
        $sheet = $obj->getActiveSheet();
        $row = sizeof($data);
        for ($j = $start_row; $j < $row + $start_row; ++$j) {
            $i = 'A';

            $sheet->getRowDimension($j)->setRowHeight(100);

            foreach ($data[$j - $start_row] as $key => $value) {
                if ($word == $key) {
                    $image = $value;

                    $objDrawing = new \PHPExcel_Worksheet_MemoryDrawing();
                    // 截取图片的格式，用不同的方法
                    $end = substr($image, -3);

                    if ('jpg' == $end || 'peg' == $end) {
                        $img = @imagecreatefromjpeg($image);
                    } elseif ('png' == $end) {
                        $img = @imagecreatefrompng($image);
                    } elseif ('gif' == $end) {
                        $img = @imagecreatefromgif($image);
                    }

                    $objDrawing->setImageResource($img);
                    $objDrawing->setRenderingFunction(\PHPExcel_Worksheet_MemoryDrawing::RENDERING_DEFAULT); //渲染方法

                    $objDrawing->setMimeType(\PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT);
                    // // 设置宽度高度
                    $objDrawing->setHeight(100); //照片高度
                    $objDrawing->setWidth(100); //照片宽度

                    // /*设置图片要插入的单元格*/
                    $objDrawing->setCoordinates($i . $j);
                    $objDrawing->setWorksheet($sheet);
                } elseif (is_numeric($value)) {
                    $sheet->setCellValueExplicit($i . $j, $value, \PHPExcel_Cell_DataType::TYPE_STRING)
                        ->getStyle($i . $j)->getNumberFormat()->setFormatCode('@');
                } else {
                    $sheet->setCellValue($i . $j, $value);
                }
                ++$i;
            }
        }

        if ('' == $file_name) {
            $file_name = date('YmdHis', time());
        }

        ob_end_clean();
        $objWriter = \PHPExcel_IOFactory::createWriter($obj, 'Excel2007');

        if (!empty($way)) {
            $objWriter->save($way);
            return true;
        }

        header('Content-Type: application/force-download');
        header('Content-Type: application/octet-stream');
        header('Content-Type: application/download');
        header('Content-Disposition:inline;filename="' . $file_name . '.xls"');
        header('Content-Transfer-Encoding: binary');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: no-cache');
        $objWriter->save('php://output');
        return ['status' => true];
    }
}

if (!function_exists('templatesArrTrans')) {
    /**
     * 读取的导入数据, 根据模板索引配置获取数据数组, 并过滤不在模板索引配置中的列.
     *
     * @param  array  data 传入读取excel的得到的列数字索引数组
     * @return array templates 传入对应的 字段名 => 列数字索引 配置数组
     */
    function templatesArrTrans($data, $templates, $status = false)
    {
        if (empty($data) || empty($templates)) {
            return false;
        }

        $trans_data = [];

        if ($status) {
            foreach ($data as $data_item) {
                $trans_item = [];

                foreach ($templates as $field_name => $column_index) {
                    if (isset($data_item[$column_index])) {
                        $tmp = trim(htmlspecialchars(nl2br($data_item[$column_index])));

                        if (checkDateTime($tmp)) {
                            $trans_item[$field_name] = strtotime($tmp);
                        } else {
                            $trans_item[$field_name] = $tmp;
                        }
                    }
                }

                $trans_data[] = $trans_item;
            }
        } else {
            foreach ($data as $data_item) {
                $trans_item = [];

                foreach ($templates as $field_name => $column_index) {
                    if (isset($data_item[$column_index])) {
                        $trans_item[$field_name] = trim(htmlspecialchars(nl2br($data_item[$column_index])));
                    }
                }

                $trans_data[] = $trans_item;
            }
        }

        return $trans_data;
    }
}

if (!function_exists('checkDateTime')) {
    /**
     * 判断数据是否为时间类型.
     *
     * @param  string  data 字段值
     * @return bool 是否为时间类型
     */
    function checkDateTime($date)
    {
        $patten = '/^\\d{4}[\\-](0?[1-9]|1[012])[\\-](0?[1-9]|[12][0-9]|3[01])(\\s+(0?[0-9]|1[0-9]|2[0-3])\\:(0?[0-9]|[1-5][0-9])(\\:(0?[0-9]|[1-5][0-9]))?)?$/';

        if (preg_match($patten, $date)) {
            return true;
        }
        return false;
    }
}

if (!function_exists('getConfigCode')) {
    /**
     * 读取国别,币制,计量单位代码文件.
     * @param  $data =country currency unit district
     * @return array $array
     *               add by guo 2018年7月14日
     */
    function getConfigCode($data)
    {
        $str = trim(file_get_contents(env('ROOT_PATH') . 'private/json/' . $data . '_json.txt'));

        $str = mb_convert_encoding($str, 'UTF-8', 'UTF-8,GBK,GB2312,BIG5'); //转换字符集（编码）

        return json_decode(trim($str), true); //如果转化不成功则大几率是文件存在空白字符问题
    }
}

if (!function_exists('generateBillNo')) {
    /**
     * 支持传入特定前缀, 生成系统单据号.
     *
     * @param  array prefix 单据前缀
     * @return string 系统单据号
     */
    function generateBillNo($prefix = '')
    {
        return $prefix . date('ymd') . substr(substr(microtime(), 2, 6)
        * time(), 2, 6) . mt_rand(1000, 9999);
    }
}

if (!function_exists('exportSheetFile')) {
    function exportSheetFile($file_path, $data, $file_name = '', $way = '')
    {
        //读取demo数据
        $file = $file_path;
        if (!file_exists($file)) {
            return ['status' => false, 'message' => '找不到模板文件' . $file];
        }

        $obj = \PHPExcel_IOFactory::load($file);

        foreach ($data as $k => $v) {
            $sheet = $obj->getSheet($v['sheet']);
            $start_row = $v['start_row'];
            $data = $v['list'];
            $row = sizeof($data);

            for ($j = $start_row; $j < $row + $start_row; ++$j) {
                $i = 'A';
                foreach ($data[$j - $start_row] as $key => $value) {
                    if (is_numeric($value)) {
                        $sheet->setCellValueExplicit($i . $j, $value, \PHPExcel_Cell_DataType::TYPE_STRING)
                            ->getStyle($i . $j)->getAlignment()->setWrapText(true);
                    } else {
                        $sheet->setCellValue($i . $j, $value)->getStyle($i . $j)->getAlignment()->setWrapText(true);
                    }
                    ++$i;
                }
            }
        }

        if ('' == $file_name) {
            $file_name = date('YmdHis', time());
        }

        ob_end_clean();
        $objWriter = \PHPExcel_IOFactory::createWriter($obj, 'Excel2007');

        if (!empty($way)) {
            $objWriter->save($way);
            return true;
        }

        header('Content-Type: application/force-download');
        header('Content-Type: application/octet-stream');
        header('Content-Type: application/download');
        header('Content-Disposition:inline;filename="' . $file_name . '.xlsx"');
        header('Content-Transfer-Encoding: binary');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: no-cache');
        $objWriter->save('php://output');
        return ['status' => true];
    }

    //判断该字符串是否为 Json格式
    function isJson($data = '', $assoc = false)
    {
        $data = json_decode($data, $assoc);
        if (($data && is_object($data)) || (is_array($data) && !empty($data))) {
            return $data;
        }
        return false;
    }
}

if (!function_exists('createToken')) {
    //生成token
    function createToken($str)
    {
        return sha1($str) . md5($str);
    }
}
